<?php

$artist = $_REQUEST['artist'];
$album  = $_REQUEST['album'];
$type = $_REQUEST['type'];

if ($album) {
  $type = 'album';
 } else {
  $type = 'artist';
 }

if (!$artist && !$album) {
  echo '<form action="' . $_SERVER['PHP_SELF'] . '">';
  echo 'Artist: <input name="artist" size="50"><br/>';
  echo 'Album: <input name="album" size="50"><br/>';
  echo '<input type="submit" value="Search">';
  echo '</form>';
  return;
 }

header('Content-type: text/xml');

define(BASE,'http://www.gracenote.com/');
define(SEP,"\t");

function clean($msg) {
  $msg = preg_replace("/\"/","\\\"",$msg);
  return htmlspecialchars($msg);
}

# Search for the album
$albumsURL = NULL;
$url = BASE . 'search/?query=' . urlencode($artist) . '&search_type=artist';
$lines = file($url);
foreach ($lines as $ln) {
  # <a href="/search/artist.php?contributor_id=280">
    if (preg_match('/<a href=\"(\/search\/artist.php\?contributor_id=\d+)\">/',$ln,$out)) {
      $albumsURL = BASE . $out[1];
    }
}

$albumURL = NULL;
$albumName = NULL;
$lines = file($albumsURL);
if ($type == 'artist') {
  echo '<artist name="' . clean($artist) . '">';
  echo '<albums>';
 }
foreach ($lines as $ln) {
  #<div class="album-title"><strong><a href="/search/album_details.php?tui_id=87571389">Make Believe</a>
    if (preg_match('/<div class="album-title"><strong><a href="(\/search\/album_details.php\?tui_id=\d++)">([^<]+)<\/a>/',$ln,$out)) {
      $url = BASE . $out[1];
      $name = $out[2];
      if ($type == 'artist') {
        echo '<album name="' . clean($name) . '" url="' . clean($url) . '" />';
      }
      if ($type == 'album') {
        if (preg_match('/' . $album . '/i',$name)) {
          $albumURL = $url;
          $albumName = $name;
        }
      }
    }
}
if ($type == 'artist') {
  echo '</albums>';
  echo '</artist>';
  return;
 }

if ($type == 'album') {
  echo '<album name="' . clean($albumName) . '" artist="' . clean($artist) . '" url="' . clean($albumURL) . '">';
  echo '<tracks>';
 }
$lines = file($albumURL);
foreach ($lines as $ln) {
  # <div class="track_name">Tired of Sex</div>
    if (preg_match('/<div class="track_name">([^<]+)<\/div>/',$ln,$out)) {
      $name = $out[1];
      if ($type == 'album') {
        echo '<track name="' . clean($name) . '" />';
      }
    }
}
if ($type == 'album') {
  echo '</tracks>';
  echo '</album>';
 }

?>